require 'apr.oo'
local apr, tostring, type, table, pairs, print =
      apr, tostring, type, table, pairs, print

module('apr.mime')

--- Opposite of parse_headers, take a table of header name: value pairs and serialize them to a string
-- @param header_table the headers as key: value pairs
-- @param line_limit the maximum length of a line including the \r\n - defaults to 80
function unparse_headers(header_table, line_limit)
    line_limit = line_limit or 80
    header_lines = {}
    for k, v in pairs(header_table) do
        if type(v) ~= 'string' then v = tostring(v) end
        
        if k:len() + v:len() + 4 <= line_limit then
            header_lines[#header_lines + 1] = k .. ': ' .. v
        else
            local start_next = line_limit - (k:len() + 3)
            local value_len = v:len()
            header_lines[#header_lines + 1] = k .. ': ' .. v:sub(1, start_next - 1)
            while start_next < value_len do
                header_lines[#header_lines + 1] = ' ' .. v:sub(start_next, start_next + (line_limit - 4))
                start_next = start_next + (line_limit - 4) + 1
            end
        end
    end
    
    return table.concat(header_lines, '\r\n')
end
